/**
 * 性能优化服务集成模块
 * 统一导出所有优化服务，提供便捷的集成接口
 */

// 导出所有服务
export { CacheManager, globalCacheManager, logDataCache, dumpPathCache, componentCache } from '../utils/cacheManager'
export { DataLoaderService, dataLoaderService, LoadPriority } from './dataLoaderService'
export { RenderOptimizationService, renderOptimizationService, RenderPhase } from './renderOptimizationService'
export { MemoryManagementService, memoryManagementService } from './memoryManagementService'
export { DumpCacheService, dumpCacheService } from './dumpCacheService'
export { PerformanceOptimizationService, performanceOptimizationService } from './performanceOptimizationService'

// 导出类型定义
export type { CacheEntry, CacheConfig, CacheStats } from '../utils/cacheManager'
export type { LogData, ComponentInfo, DumpFileInfo as DataLoaderDumpFileInfo } from './dataLoaderService'
export type { RenderTask, VirtualizationConfig } from './renderOptimizationService'
export type { MemoryThresholds, MemoryStats, CleanupStrategy, CleanupResult } from './memoryManagementService'
export type { DumpFileInfo, DumpDataCacheItem, DumpCacheStats } from './dumpCacheService'
export type { PerformanceMetrics, OptimizationConfig, OptimizationStatus } from './performanceOptimizationService'

import { performanceOptimizationService } from './performanceOptimizationService'
import { dataLoaderService } from './dataLoaderService'
import { renderOptimizationService } from './renderOptimizationService'
import { memoryManagementService } from './memoryManagementService'
import { dumpCacheService } from './dumpCacheService'

/**
 * 性能优化集成服务
 * 提供统一的初始化和管理接口
 */
export class PerformanceIntegrationService {
  private isInitialized = false
  private initializationPromise?: Promise<void>

  /**
   * 初始化所有性能优化服务
   */
  async initialize(config?: {
    enableCaching?: boolean
    enableMemoryManagement?: boolean
    enablePreloading?: boolean
    memoryThresholds?: {
      warning: number
      critical: number
      maximum: number
    }
  }): Promise<void> {
    if (this.isInitialized) {
      console.log('[PerformanceIntegration] 服务已初始化')
      return
    }

    if (this.initializationPromise) {
      return this.initializationPromise
    }

    this.initializationPromise = this.doInitialize(config)
    return this.initializationPromise
  }

  private async doInitialize(_config?: any): Promise<void> {
    console.log('[PerformanceIntegration] 开始初始化性能优化服务')
    
    try {
      // 初始化主性能优化服务
      await performanceOptimizationService.initialize()
      
      console.log('[PerformanceIntegration] 所有性能优化服务初始化完成')
      this.isInitialized = true
      
    } catch (error) {
      console.error('[PerformanceIntegration] 初始化失败:', error)
      throw error
    }
  }

  /**
   * 优化工作区
   */
  async optimizeWorkspace(workspaceId: string): Promise<void> {
    if (!this.isInitialized) {
      await this.initialize()
    }
    
    return performanceOptimizationService.optimizeWorkspace(workspaceId)
  }

  /**
   * 预加载工作区数据
   */
  async preloadWorkspaceData(workspaceId: string): Promise<void> {
    console.log(`[PerformanceIntegration] 预加载工作区数据: ${workspaceId}`)
    
    try {
      // 并行执行预加载任务
      await Promise.allSettled([
        dataLoaderService.preloadCriticalData(workspaceId),
        dumpCacheService.scanDumpFiles(workspaceId)
      ])
      
      console.log(`[PerformanceIntegration] 工作区数据预加载完成: ${workspaceId}`)
    } catch (error) {
      console.error(`[PerformanceIntegration] 预加载失败: ${workspaceId}`, error)
    }
  }

  /**
   * 启动分阶段渲染
   */
  async startPhaseRendering(workspaceId: string): Promise<void> {
    return renderOptimizationService.startPhaseRendering(workspaceId)
  }

  /**
   * 清理工作区缓存
   */
  clearWorkspaceCache(workspaceId: string): void {
    console.log(`[PerformanceIntegration] 清理工作区缓存: ${workspaceId}`)
    
    dataLoaderService.clearWorkspaceCache(workspaceId)
    dumpCacheService.clearWorkspaceDumpCache(workspaceId)
  }

  /**
   * 获取性能统计信息
   */
  getPerformanceStats() {
    return {
      performance: performanceOptimizationService.getPerformanceMetrics(),
      cache: performanceOptimizationService.getCacheStats(),
      render: performanceOptimizationService.getRenderStats(),
      dump: dumpCacheService.getDumpCacheStats(),
      optimization: performanceOptimizationService.getOptimizationStatus()
    }
  }

  /**
   * 获取内存统计信息
   */
  async getMemoryStats() {
    return await memoryManagementService.getMemoryStats()
  }

  /**
   * 执行内存清理
   */
  async performMemoryCleanup(): Promise<void> {
    await memoryManagementService.performSmartCleanup()
  }

  /**
   * 生成性能报告
   */
  async generatePerformanceReport() {
    const [performanceStats, memoryStats] = await Promise.allSettled([
      Promise.resolve(this.getPerformanceStats()),
      this.getMemoryStats()
    ])

    return {
      performance: performanceStats.status === 'fulfilled' ? performanceStats.value : null,
      memory: memoryStats.status === 'fulfilled' ? memoryStats.value : null,
      timestamp: Date.now(),
      suggestions: performanceOptimizationService.getOptimizationSuggestions()
    }
  }

  /**
   * 销毁所有服务
   */
  destroy(): void {
    console.log('[PerformanceIntegration] 销毁所有性能优化服务')
    
    performanceOptimizationService.destroy()
    renderOptimizationService.destroy()
    memoryManagementService.destroy()
    dumpCacheService.destroy()
    
    this.isInitialized = false
    this.initializationPromise = undefined
  }

  /**
   * 检查服务状态
   */
  getServiceStatus() {
    return {
      initialized: this.isInitialized,
      optimizationStatus: performanceOptimizationService.getOptimizationStatus(),
      memoryMonitoring: memoryManagementService.getThresholds()
    }
  }
}

// 全局性能集成服务实例
export const performanceIntegrationService = new PerformanceIntegrationService()

/**
 * 便捷函数：快速初始化性能优化
 */
export async function initializePerformanceOptimization(config?: {
  enableCaching?: boolean
  enableMemoryManagement?: boolean
  enablePreloading?: boolean
  memoryThresholds?: {
    warning: number
    critical: number
    maximum: number
  }
}): Promise<void> {
  return performanceIntegrationService.initialize(config)
}

/**
 * 便捷函数：优化工作区性能
 */
export async function optimizeWorkspacePerformance(workspaceId: string): Promise<void> {
  return performanceIntegrationService.optimizeWorkspace(workspaceId)
}

/**
 * 便捷函数：预加载工作区数据
 */
export async function preloadWorkspaceData(workspaceId: string): Promise<void> {
  return performanceIntegrationService.preloadWorkspaceData(workspaceId)
}

/**
 * 便捷函数：清理工作区缓存
 */
export function clearWorkspaceCache(workspaceId: string): void {
  performanceIntegrationService.clearWorkspaceCache(workspaceId)
}

/**
 * 便捷函数：获取性能统计
 */
export function getPerformanceStats() {
  return performanceIntegrationService.getPerformanceStats()
}

/**
 * 便捷函数：执行内存清理
 */
export async function performMemoryCleanup(): Promise<void> {
  return performanceIntegrationService.performMemoryCleanup()
}

/**
 * 便捷函数：生成性能报告
 */
export async function generatePerformanceReport() {
  return performanceIntegrationService.generatePerformanceReport()
}

// 默认导出集成服务
export default performanceIntegrationService